package com.hnkywl.sts.dao.cggl;

import com.hnkywl.sts.dao.base.RegionDao;
import com.hnkywl.sts.entity.cggl.Glfy;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.*;
import org.hibernate.type.Type;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-5-2
 * Time: 下午5:25
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class GlfyDao extends SimpleHibernateTemplate<Glfy, Long> {
    public List<Glfy> findGlfyList(Long sydwGsId, Long wlsId, String wlsqc, String gldh, Long wljsdId, Integer wljsdZt) {
        String hql = null;
        List<Object> param = new ArrayList<Object>();
        StringBuilder condition = new StringBuilder();
        Page<Glfy> page = new Page<Glfy>(1, 1000, 0);
        //==============条件拼接===============
        if (wljsdId != null) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" wljsd.id = ? ");
            param.add(wljsdId);
        }
        if (wljsdZt != null) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" zt = ? ");
            param.add(wljsdZt);
        }
        if (sydwGsId != null) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" createOrgan.id = ? ");
            param.add(sydwGsId);
        }
        if (wlsId != null) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" sydw.id = ? ");
            param.add(wlsId);
        }
        if (wlsqc != null && !"".equals(wlsqc)) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" sydw.qc like ? ");
            param.add("%" + wlsqc.trim() + "%");
        }
        if(gldh != null && !"".equals(gldh)){
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append("( cgd.id = (select id from Cgd a where a.cgdh like ? ) or xsd.id = (select id from Xsd b where b.xsdh like ? ) or gldh like ? )");
            param.add("%" + gldh.trim() + "%");
            param.add("%" + gldh.trim() + "%");
            param.add("%" + gldh.trim() + "%");
        }
        //==============记录数量===============
//        hql = "select count(*) from Glfy where (cgd.id in(select id from Cgd a where a.deleted != 1) or xsd.id in (select id from Xsd b where b.deleted != 1) or csh=1)";
//        if (condition.length() != 0)
//            hql = hql + " and " + condition;
//        Long c = null;
//        if (param.size() != 0) {
//            c = (Long) findUnique(hql, param.toArray());
//            page.setTotalCount(c.intValue());
//        } else {
//            c = (Long) findUnique(hql);
//            page.setTotalCount(c.intValue());
//        }
//        if (c == 0)
//            return page;
        //==============查询结果===============
        hql = "from Glfy where (cgd.id in (select id from Cgd a where a.deleted != 1) or xsd.id in (select id from Xsd b where b.deleted != 1) or csh=1)";
        if (condition.length() != 0)
            hql = hql + " and " + condition;
        hql = hql + " order by dateCreated desc";
        return  createQuery(hql, param.toArray()).list();
    }

    //   当前日期加减n天后的日期，返回String   (yyyy-mm-dd)
    public Date jDaysAfterNowDate(Date date) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.set(java.util.Calendar.HOUR_OF_DAY, 23);
        rightNow.set(java.util.Calendar.MINUTE, 59);
        rightNow.set(java.util.Calendar.SECOND, 59);
        return rightNow.getTime();
    }

    //   当前日期加减n天后的日期，返回String   (yyyy-mm-dd)
    public Date sDaysAfterNowDate(Date date) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.set(java.util.Calendar.HOUR_OF_DAY, 0);
        rightNow.set(java.util.Calendar.MINUTE, 0);
        rightNow.set(java.util.Calendar.SECOND, 0);
        return rightNow.getTime();
    }

    public Page findAllGlfyList(String djh, String ywlx, Long fylbId, Long sydwId, String jszt, Long cgdwId, Date zdsjStart, Date zdsjEnd, int pageNo, int pageSize) {
        Page<Map> page = new Page<Map>();
        page.setAutoCount(true);
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        Criteria criteria = getSession().createCriteria(this.entityClass)
                .createAlias("cgd", "cgd", CriteriaSpecification.LEFT_JOIN)
                .createAlias("xsd", "xsd", CriteriaSpecification.LEFT_JOIN)
                .createAlias("sydw", "sydw", CriteriaSpecification.LEFT_JOIN)
                .createAlias("fylb", "fylb", CriteriaSpecification.LEFT_JOIN)
                .createAlias("createOrgan", "createOrgan", CriteriaSpecification.LEFT_JOIN)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("id").as("id"))
                        .add(Property.forName("cgd.id").as("cgd.id"))
                        .add(Property.forName("xsd.id").as("xsd.id"))
                        .add(Projections.sqlProjection("cgd1_.cgdh as cgdh", new String[]{"cgdh"}, new Type[]{Hibernate.STRING}))
                        .add(Projections.sqlProjection("xsd2_.xsdh as xsdh", new String[]{"xsdh"}, new Type[]{Hibernate.STRING}))
                        .add(Projections.sqlProjection("this_.gldh as gldh", new String[]{"gldh"}, new Type[]{Hibernate.STRING}))
                        .add(Projections.sqlProjection("sydw3_.id as sydwid", new String[]{"sydwid"}, new Type[]{Hibernate.LONG}))
                        .add(Property.forName("sydw.jc").as("sydw.jc"))
                        .add(Property.forName("fylb.fykmjc").as("fylb.fykmjc"))
                        .add(Property.forName("jfsl").as("jfsl"))
                        .add(Property.forName("dj").as("dj"))
                        .add(Property.forName("je").as("je"))
                        .add(Projections.sqlProjection("this_.CREATEORGAN_ID as CREATEORGAN_ID", new String[]{"CREATEORGAN_ID"}, new Type[]{Hibernate.LONG}))
                        .add(Property.forName("createOrgan.jc").as("gs.jc"))
                        .add(Projections.sqlProjection("this_.date_created as date_created", new String[]{"date_created"}, new Type[]{Hibernate.DATE}))
                )
                .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
        if (StringUtils.isNotEmpty(djh)) {
            criteria.add(
                    Restrictions.or(
                            Restrictions.or(Restrictions.like("cgd.cgdh", djh, MatchMode.ANYWHERE),
                                    Restrictions.like("xsd.xsdh", djh, MatchMode.ANYWHERE)),
                            Restrictions.like("gldh", djh, MatchMode.ANYWHERE)));
        }

        if (zdsjStart != null) {
            criteria.add(Restrictions.ge("dateCreated", sDaysAfterNowDate(zdsjStart)));
        }
        if (zdsjEnd != null) {
            criteria.add(Restrictions.le("dateCreated", jDaysAfterNowDate(zdsjEnd)));
        }

        if (StringUtils.isNotEmpty(ywlx)) {
            if (ywlx.equals("cgd")) {
                criteria.add(Restrictions.or(Restrictions.isNotNull("cgd"), Restrictions.eq("type", 1)));
            } else if (ywlx.equals("xsd")) {
                criteria.add(Restrictions.or(Restrictions.isNotNull("xsd"), Restrictions.eq("type", 2)));
            }
        }

        if (StringUtils.isNotEmpty(jszt)) {
            if (jszt.equals("wjs")) {
                criteria.add(Restrictions.isNull("wljsd"));
            } else if (jszt.equals("yjs")) {
                criteria.add(Restrictions.isNotNull("wljsd"));
            }
        }

        if (fylbId != null) {
            criteria.add(Property.forName("fylb.id").eq(fylbId));
        }

        if (sydwId != null) {
            criteria.add(Property.forName("sydw.id").eq(sydwId));
        }

        if (cgdwId != null) {
            criteria.add(Property.forName("createOrgan.id").eq(cgdwId));
        }

        criteria.add(Restrictions.or(
                Restrictions.or(Restrictions.isNotNull("cgd"),Restrictions.isNotNull("xsd")),
                Restrictions.isNotNull("gldh")));
        RegionDao.createDataRegion(criteria);

        criteria.addOrder(Property.forName("id").desc());

        Page list = this.findByCriteria(page, criteria);
        return list;
    }
}
